package com.cnhis.onehis.util;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.SqlSession;

import com.cnhis.cloudhealth.clinical.util.ExUtil;
import com.cnhis.onehis.MybatisUtil;

public class DbUtil {

	public static List<Map> rs2List(ResultSet rs1) {
		// TODO Auto-generated method stub
		return convertList(  rs1);
	}
	private String cfg;
	private Statement getStt(Connection conn2) {
		Statement st = null;
		try {
			// conn.setAutoCommit(true);
			st = conn2.createStatement();
		} catch (SQLException e1) {
			ExUtil.throwExV2(e1);
		}

		return st;
	}
	
	public static long newNextid(long startPrkColLong, int i_step) {
		 
		return startPrkColLong+i_step;
	}

	public Connection conn;
	public long getMaxLong(String tab, String prkCol) {
		//SqlSession ss = MybatisUtil.getSqlSession(cfg);
		//  conn = ss.getConnection();
		Statement Statement1 = getStt(conn);
		long startTime = System.currentTimeMillis();
		try {
			ResultSet rs1 = Statement1.executeQuery("select  max(" + prkCol + ") as id from " + tab);
			List<Map> li = DbUtil.rs2List(rs1);
			if(li.size()==0) //empty tab
				return 1;
			Map map = li.get(1);
			
			return Long.parseLong(map.get(prkCol).toString());
		} catch (SQLException e) {
			ExUtil.throwExV2(e);
		}
		return -1;

	}
	public static   List convertList(ResultSet rs)  
	
	{
		if(rs ==null)
			throw new RuntimeException(" RS is  null"); 
		
		try {
			  List list = new ArrayList();
		        ResultSetMetaData md = rs.getMetaData();
		        int columnCount = md.getColumnCount();
		        while (rs.next()) {
		            Map rowData = new HashMap();
		            for (int i = 1; i <= columnCount; i++) {
		                rowData.put(md.getColumnName(i), rs.getObject(i));
		            }
		            list.add(rowData);
		        }
		        return list;
		} catch (Exception e) {
			ExUtil.throwExV2(e);
		}
		return null;
      
}

}
